import axios from "axios";

function timestamp() {
    let t = new Date()
    let year = t.getFullYear().toString();
    var month = (t.getMonth() + 1).toString();
    if (month.length < 2) month = "0" + month;
    var date = t.getDate().toString();
    if (date.length < 2) date = "0" + date;
    var hours = t.getHours().toString();
    if (hours.length < 2) hours = "0" + hours;
    var mintues = t.getMinutes().toString();
    if (mintues.length < 2) mintues = "0" + mintues;
    var seconds = t.getSeconds().toString();
    if (seconds.length < 2) seconds = "0" + seconds;
    return `${year}-${month}-${date} ${hours}:${mintues}:${seconds}`
}

interface SendTemplateBody {
    touser: string;
    template_id: string;
    page?: string;
    form_id: string; // 表单提交场景下，为 submit 事件带上的 formId；支付场景下，为本次支付的 prepay_id
    data: { [keyword: string]: string };
    emphasis_keyword?: string;
}

interface APIResponse {
    errcode: number;
    errmsg: string;
}

export default class WechatMicro {
    protected appid: string;
    protected secret: string;
    private access_token: string;
    private access_token_expired_at: number;
    constructor(appid: string, secret: string) {
        this.appid = appid;
        this.secret = secret;
    }

    async getAccessToken(): Promise<string> {
        return '';
    }

    async sendTemplate(body: SendTemplateBody): Promise<APIResponse> {
        let url = `https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=` + await this.getAccessToken()
        let data = {};
        for (let k in body.data) {
            let v = body.data[k]
            data[k] = { value: v }
        }
        let ret = await axios.post(url, Object.assign(body, { data }))
        return ret.data;
    }

    sendNotice(open_id: string, form_id: string, title: string, remark?: string) {
        return this.sendTemplate({
            touser: open_id,
            template_id: '6N3U2UJ0FbY7JgePcVvVc5Skl3g9edS9Wwk6Egwub5s',
            form_id,
            data: {
                keyword1: title,
                keyword2: remark,
                keyword3: timestamp(),
            },
            emphasis_keyword: 'keyword1',
        })
    }
} 